// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <melon/function.h>

#include "melon/synchronization/call_once.h"
#include <pollux/common/base/gtest_macros.h>
#include <pollux/dwio/common/int_decoder.h>
#include <pollux/dwio/dwrf/common/common.h>
#include <pollux/vector/base_vector.h>

namespace kumo::pollux::dwrf {
class StripeDictionaryCache {
 public:
  explicit StripeDictionaryCache(pollux::memory::MemoryPool* pool);

  void registerIntDictionary(
      const EncodingKey& encodingKey,
      melon::Function<BufferPtr(pollux::memory::MemoryPool*)>&& dictGen);

  BufferPtr getIntDictionary(const EncodingKey& encodingKey);

 private:
  // This could be potentially made an interface to be shared for string
  // dictionaries. However, we will need a union return type in that case.
  class DictionaryEntry {
   public:
    explicit DictionaryEntry(
        melon::Function<BufferPtr(pollux::memory::MemoryPool*)>&& dictGen);

    BufferPtr getDictionaryBuffer(pollux::memory::MemoryPool* pool);

   private:
    melon::Function<BufferPtr(pollux::memory::MemoryPool*)> dictGen_;
    BufferPtr dictionaryBuffer_;
    melon::once_flag onceFlag_;
  };

  // This is typically the reader's memory pool.
  memory::MemoryPool* const pool_;
  melon::F14FastMap<
      EncodingKey,
      std::unique_ptr<DictionaryEntry>,
      EncodingKeyHash>
      intDictionaryFactories_;

  POLLUX_FRIEND_TEST(StripeDictionaryCacheTest, RegisterDictionary);
};

} // namespace kumo::pollux::dwrf
